package com.gombe.credit.app.request

import android.os.Handler
import android.os.Looper
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.configs.GombeCreditConfigs
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.utils.aes.GombeCreditAesUtil
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.app.utils.log.JsonFormat
import org.json.JSONObject
import java.io.IOException


/**
 * HttpLoader
 * @Author wwdeng
 * @CreateTime: 2024/11/20 17:38
 * @Annotation：网络请求
 */
class HttpLoader: IHttpLoader {
    private val mainHandler = Handler(Looper.getMainLooper())
    /**
     * post 请求
     */
    override fun post(url: String, params: JSONObject,callback: IHttpCallback) {
        //统一添加通用参数
        params.addCommonParams()
        val aesParams = GombeCreditAesUtil.encryptDefault(params.toString())
        GombeCreditLogger.i("HttpUrl：  $url")
        GombeCreditLogger.i("HttpParams： $params")
        GombeCreditLogger.i("HttpParams AES：  $aesParams")

        val headers = HashMap<String,String>()
        headers["appid"] = GombeCreditConfigs.GOMBECREDIT_APPNAME
        headers["product"] = GombeCreditConfigs.GOMBECREDIT_APPNAME

        // 创建重试请求数据
        val retryRequest = NetworkErrorManager.RetryRequest(
            requestType = "POST",
            url = url,
            params = params, // 保存原始参数，用于重试
            headers = headers,
            originalCallback = callback
        )

        OkHttpUtil.getInstance().postJson(url, aesParams,headers,object: OkHttpUtil.HttpCallback {
            override fun onSuccess(response: String?) {
                mainHandler.post {
                    callback.onRequestFinish()
                }
                response?.let {
                    val result = GombeCreditAesUtil.decryptDefault(it)
                    Thread {
                        GombeCreditLogger.i(
                            "\nurl: $url \n" +
                                    "path: ${params.optString("path")} \n" +
                                    "response: ${JsonFormat.format(result)}"
                        )
                    }.start()

                    val data = JSONObject(result)
                    when(val code = data.optInt("code")){
                        0 -> {
                            mainHandler.post { callback.onRequestSuccess(data) }
                        }
                        else -> {
                            val errorObj = JSONObject()
                            errorObj.put("errorCode",code)
                            errorObj.put("errorMsg",data.optString("msg"))
                            mainHandler.post {
                                callback.onRequestError(errorObj)
                            }
                        }
                    }
                }
            }

            override fun onFailure(error: OkHttpUtil.NetworkError?) {
                GombeCreditLogger.i(
                    "\nurl: $url \n" +
                            "path: ${params.optString("path")} \n" +
                            "error: ${error?.message}"
                )

                //是否应该显示全局错误对话框
                if (NetworkErrorManager.shouldShowErrorDialog(error)){
                    // 显示全局网络错误提示，并传递重试请求数据
                    NetworkErrorManager.handleNetworkError(error, retryRequest)
                } else {
                    val errorObj = JSONObject()
                    errorObj.put("errorCode",-1)
                    errorObj.put("errorMsg",error?.message)
                    mainHandler.post {
                        callback.onRequestError(errorObj)
                    }
                }
                mainHandler.post {
                    callback.onRequestFinish()
                }
            }
        })
    }

    /**
     * 文件上传
     */
    override fun upload(filePath: String, callback: IHttpCallback) {
        if (filePath.isEmpty()){
            return
        }
        val headers = HashMap<String,String>()
        headers["appid"] = GombeCreditConfigs.GOMBECREDIT_APPNAME
        headers["product"] = GombeCreditConfigs.GOMBECREDIT_APPNAME

        val httpUrl = GombeCreditApiUrl.takeUploadFileUrl()

        // 创建重试请求数据
        val retryRequest = NetworkErrorManager.RetryRequest(
            requestType = "UPLOAD",
            url = httpUrl,
            params = filePath, // 保存文件路径，用于重试
            headers = headers,
            originalCallback = callback
        )

        OkHttpUtil.getInstance()
            .uploadFile(httpUrl, "image", filePath,null,headers,object: OkHttpUtil.HttpCallback {
                override fun onSuccess(response: String?) {
                    mainHandler.post {
                        callback.onRequestFinish()
                    }
                    response?.let {
                        Thread {
                            GombeCreditLogger.i(
                                "\nurl: $httpUrl \n" +
                                        "imgPath: $filePath \n" +
                                        "response: ${JsonFormat.format(it)}"
                            )
                        }.start()

                        val data = JSONObject(it)
                        when(val code = data.optInt("code")){
                            0 -> {
                                mainHandler.post { callback.onRequestSuccess(data) }
                            }
                            else -> {
                                val errorObj = JSONObject()
                                errorObj.put("errorCode",code)
                                errorObj.put("errorMsg",data.optString("msg"))
                                mainHandler.post {
                                    callback.onRequestError(errorObj)
                                }
                            }
                        }
                    }
                }
                override fun onFailure(error: OkHttpUtil.NetworkError?) {
                    GombeCreditLogger.i(
                        "\nurl: $httpUrl \n" +
                                "imgPath: $filePath \n" +
                                "error: ${error?.message}"
                    )
                    if (NetworkErrorManager.shouldShowErrorDialog(error)){
                        // 显示全局网络错误提示，并传递重试请求数据
                        NetworkErrorManager.handleNetworkError(error, retryRequest)
                    } else {
                        val errorObj = JSONObject()
                        errorObj.put("errorCode",-1)
                        errorObj.put("errorMsg",error?.message)
                        mainHandler.post {
                            callback.onRequestError(errorObj)
                        }
                    }
                    mainHandler.post {
                        callback.onRequestFinish()
                    }
                }
        })
    }

    /**
     * 添加打点事件
     */
    override fun addPoint(eventName: String, remark: String?, callback: IHttpCallback) {
        GombeCreditLogger.e(">>>>>>>>>>>>>>eventName：$eventName，remark：$remark")
        val eventType = eventName.uppercase()//转大写
        if (remark != null){
            GombeCreditPointManager.getInstance().track(eventType,remark)
        } else {
            GombeCreditPointManager.getInstance().track(eventType,"")
        }
//        val httpUrl = GombeCreditApiUrl.takeTrackPointUrl()
//        val params = JSONObject().addCommonParams().apply {
//            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_TRACK_EVENT_PATH)
//            put("type", eventName)
//            put("remark", remark)
//        }
//        post(httpUrl,params,callback)
    }

    /**
     * 设置请求tag
     */
    override fun setTag(tag: Any) {
    }

    /**
     * 取消请求
     */
    override fun cancelTag(tag: Any) {
    }
}